package com.llmm.eduService.controller;

import com.llmm.exception.CommonErrorCode;
import com.llmm.exception.ExceptCase;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;

@RequestMapping("file")
@RestController
public class FileController {

    /**
     * @description: 文件上传
     * @param: [file]
     * @return: void
     * @author: llmm
     * @date: 2022/2/26
     */
    @PostMapping("/upload")
    public void fileUpload(@RequestParam("file")MultipartFile file){
        //判断文件是否为空
        if (file.isEmpty()){
            ExceptCase.cast(CommonErrorCode.E_100001);
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        // 后缀名 , 获取文件名字最后最后一次出现 “.” 的位置，并切割取它后面的字符串即为文件名。 .jpg
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 获取当前时间。 20220227000310
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis());
        //设置新的文件名  llmm20220227000310.jpg
        fileName = "llmm"+time+suffixName;

        //文件上传地址 ,一般在配置文件中取
        String filePath = "E://dowmloadfile//";
        //设置文件保持位置
        File dest = new File(filePath + fileName);
        //判断是否存在，创建
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        // 文件存放
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * @description:
     * @param: [filePath, response, isOnLine]
     * @return: void
     * @author: llmm
     * @date: 2022/2/27
     */
    public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

    // https://blog.csdn.net/qq_43068123/article/details/116198763
    /**
     * @description:
     * @param: [fileName, response]
     * @return: void
     * @author: llmm
     * @date: 2022/2/27
     */
    @GetMapping(value = "/test1")
    public void test( HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("users.xls", "UTF-8"));
        String path = "D://users.xls";
        try {
            FileInputStream in = new FileInputStream(new File(path));
            FileCopyUtils.copy(in, response.getOutputStream());
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/download")
    public void  download(HttpServletResponse res) throws IOException {
        String path = "users.xls";
        res.setCharacterEncoding("UTF-8");
        // attachment是以附件的形式下载，inline是浏览器打开
        res.setHeader("Content-Disposition", "inline;filename=users.xls");
        res.setContentType("text/plain;UTF-8");
        // 把二进制流放入到响应体中
        OutputStream os = res.getOutputStream();
        File file = new File(path);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }
}
